package cn.edu.fzu.homemaking.company.session;

import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import cn.edu.fzu.homemaking.common.SessionConstant;

public class UserSession implements HttpSession {

    private final Map<String, Object> cache = new HashMap<>();

    private final ServletContext      servletContext;

    private final String              id;
    private final long                creationTime;
    private long                      lastAccessedTime;
    private int                       maxInactiveInterval;

    public UserSession(ServletContext servletContext, String id) {
        this.servletContext = servletContext;

        this.id = id;

        this.creationTime = System.currentTimeMillis();
        this.lastAccessedTime = this.creationTime;
        this.maxInactiveInterval = SessionConstant.SESSION_TIMEOUT;
    }


    @Override
    public Object getAttribute(String name) {
        this.lastAccessedTime = System.currentTimeMillis();
        return cache.get(name);
    }


    @Override
    public void setAttribute(String name, Object value) {
        this.lastAccessedTime = System.currentTimeMillis();
        cache.put(name, value);
    }


    @Override
    public void invalidate() {
        cache.clear();
    }


    @Override
    public String getId() {
        return id;
    }


    @Override
    public long getCreationTime() {
        return creationTime;
    }


    @Override
    public long getLastAccessedTime() {
        return lastAccessedTime;
    }


    @Override
    public ServletContext getServletContext() {
        return servletContext;
    }


    @Override
    public Enumeration<String> getAttributeNames() {
        return Collections.enumeration(cache.keySet());
    }


    @Override
    public void setMaxInactiveInterval(int interval) {
        this.maxInactiveInterval = interval;
    }


    @Override
    public int getMaxInactiveInterval() {
        return maxInactiveInterval;
    }


    @Override
    public boolean isNew() {
        return this.lastAccessedTime == this.creationTime;
    }


    @Override
    public void removeAttribute(String name) {
        setAttribute(name, null);
    }


    @Override
    public String[] getValueNames() {
        throw new UnsupportedOperationException();
    }


    @Override
    public Object getValue(String name) {
        throw new UnsupportedOperationException();
    }


    @Override
    public void putValue(String name, Object value) {
        throw new UnsupportedOperationException();
    }


    @Override
    public void removeValue(String name) {
        throw new UnsupportedOperationException();
    }


    @Override
    public HttpSessionContext getSessionContext() {
        throw new UnsupportedOperationException();
    }
}
